//""
//  XSComposeView.swift
//  WeiDo
//
//  Created by XISHAN on 16/3/11.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit
import pop


class XSComposeView: UIView {

    var target:UIViewController?
    var buttons:[XSComposeButton] = [XSComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI(){
        
        frame = UIScreen.mainScreen().bounds
        backgroundColor = RandomColor()
        
        //磨砂的背影图
        let backgroundImageView = UIImageView(image: getScreenShot().applyLightEffect())
        addSubview(backgroundImageView)
        //微博广告口号
        addSubview(sloganView)
        
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        
        
        addChildButton()
    }
    
    func addChildButton(){
        
        let itemW:CGFloat = 80
        let itemH:CGFloat = 110
        
        //按钮之间的间距
        let itemMargin = (SCREENW - itemW * 3) / 4
        
        //读取按钮的数据
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        var menuInfos = [XSComposeMenuInfo]()
        
        for dict in array{
            let info = XSComposeMenuInfo(dict: (dict as! [String : AnyObject]))
            menuInfos.append(info)
        }
        
        for (i,info) in menuInfos.enumerate() {
            
            let button = XSComposeButton()
            button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //区分按钮
            button.tag = i
            
            button.frame.size = CGSize(width: itemW, height: itemH)
            //设置数据
            button.menuInfo = info
            addSubview(button)
            
            buttons.append(button)
            //求出列和行
            let col = i%3
            let row = i/3
            
            //设置x和y值
            button.frame.origin.x = CGFloat(col + 1) * itemMargin + CGFloat(col) * itemW
            button.frame.origin.y = CGFloat(row) * (itemH + itemMargin) + SCREENH
            
        }
        
    }
    
    func show(target: UIViewController) {
        target.view.addSubview(self)
        
        // 记录target,以便在点击按钮要弹出控制器的时候使用
        self.target = target
    }
    // 6个按钮点击的监听方法
    @objc private func composeButtonClick(button: XSComposeButton){
        print("点击Compose按钮了")
        
        // 放大的动画
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            for value in self.buttons {
                // 如果遍历到的是当前点击的按钮,放大并透明
                value.alpha = 0.01
                value.transform = value == button ? CGAffineTransformMakeScale(2, 2) : CGAffineTransformMakeScale(0.01, 0.01)
            }
            }, completion: { (_) in
                
                // 取到按钮显示的信息
                let menuInfo = button.menuInfo
                
                
                // print(NSStringFromClass(HMComposeViewController.self))
                
                // 根据类名去初始化控制器,注意在Swift有命名空间的前缀
                let targetClass = NSClassFromString(menuInfo!.targetVC!) as! UIViewController.Type
                // 注意:init()没有智能提示
                let vc = targetClass.init()
               
                self.target?.presentViewController(XSNavigationViewController(rootViewController: vc), animated: true, completion: {
                    self.removeFromSuperview()
                })
        })
        
    }

    deinit {
        print("我销毁啦")
    }
    
    //        let data = UIImagePNGRepresentation(image)
    //        data?.writeToFile("/Users/xiele/Desktop/哈哈.png", atomically: true)
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 执行向下的动画
        // 执行6个按钮的动画
        
        buttonsAnimation(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64((0.4 * Double(NSEC_PER_SEC)))), dispatch_get_main_queue(), {
            self.removeFromSuperview()
        });
        
    }
    
    
    /// 执行按钮的东西
    ///
    /// - parameter isUp: 是否是上来的动画
    func buttonsAnimation(isUp: Bool) {
        
        // 根据是否是上来的动画,去判断是否要返转数组
        let array = isUp ? buttons : buttons.reverse()
        
        for (index,value) in array.enumerate() {
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 指定控件执行动画的最终位置
            animation.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -330 : 330)))
            // [0,20],越大幅度越大
            animation.springBounciness = 10
            // 速度
            animation.springSpeed = 8
            // 开始时间
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            value.pop_addAnimation(animation, forKey: nil)
        }
    }

    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        
        buttonsAnimation(true)
        
    }
    


    private func getScreenShot() -> UIImage {
        
        let rect = UIScreen.mainScreen().bounds
        let window = UIApplication.sharedApplication().keyWindow
        
        //1.开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        //2.将屏幕画到上下文中
        window?.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
        //3.取到图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //4.关闭图形上下文
        UIGraphicsEndImageContext()
        //5.返回图片
        return image
        
        
        
    }
    private lazy var sloganView:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
}
